import { reqLogin, reqGetUserInfo, reqGetUserDetailById } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const state = () => {
  return {
    token: getToken() || null,
    userInfo: {}
  }
}
const mutations = {
  setToken(state, newToken) {
    // 存入vuex中
    state.token = newToken
    // 存入cookie中 持久化
    setToken(newToken)
  },

  // 清除token
  removeToken(state) {
    state.token = null
    removeToken()
  },

  // 设置用户信息
  setUserInfo(state, UserInfo) {
    state.userInfo = UserInfo
  },

  // 清除用户信息
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  // 登录
  async login(context, data) {
    const res = await reqLogin(data)
    context.commit('setToken', res.data)
    // return res
  },

  // 获取用户信息
  async getUserInfo(context) {
    // 1.基本信息
    const { data: res1 } = await reqGetUserInfo()

    // 2.信息(有头像)
    const { data: res2 } = await reqGetUserDetailById(res1.userId)

    const res = { ...res1, ...res2 }
    // console.log(res)

    context.commit('setUserInfo', res)
    // console.log(res)

    return res
  },

  // 退出
  logout(context) {
    // 1.清除token
    context.commit('removeToken')
    // 2.清除用户信息
    context.commit('removeUserInfo')

    // 3.重置用户的路由规则
    resetRouter()

    // 4.重置权限模块中的routes
    context.commit('permission/setRoutes', [], { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
